<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>WebSocket Chat Test</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }
    #chat {
      width: 300px;
      height: 400px;
      border: 1px solid #ccc;
      overflow-y: scroll;
      margin-bottom: 10px;
      padding: 10px;
    }
    .message {
      margin: 5px 0;
    }
    .message.sent {
      text-align: right;
    }
    .message.received {
      text-align: left;
    }
    .message.sent strong {
      color: blue;
    }
    .message.received strong {
      color: green;
    }
    #message {
      width: 200px;
    }
    #send {
      width: 90px;
    }
  </style>
</head>
<body>
<h1>WebSocket Chat Test</h1>
<div id="chat"></div>
<input type="text" id="message" placeholder="Type a message...">
<button id="send">Send</button>
<script>
  const username = prompt("Enter your username:");
  const socket = new WebSocket(`ws://localhost:8080/chat/${username}`);

  socket.onopen = function(event) {
    console.log("Connected to WebSocket server.");
  };

  socket.onmessage = function(event) {
    const chat = document.getElementById('chat');
    const message = JSON.parse(event.data);
    const messageElement = document.createElement('div');
    messageElement.className = 'message ' + (message.fromName === username ? 'sent' : 'received');
    messageElement.innerHTML = `<strong>${message.fromName}:</strong> ${message.message}`;
    chat.appendChild(messageElement);
    chat.scrollTop = chat.scrollHeight;
  };

  socket.onclose = function(event) {
    console.log("Disconnected from WebSocket server.");
  };

  socket.onerror = function(error) {
    console.error("WebSocket error:", error);
  };

  document.getElementById('send').addEventListener('click', function() {
    const messageInput = document.getElementById('message');
    const message = messageInput.value;
    if (message) {
      const toName = prompt("Enter the recipient's username (or leave blank for random):");
      const messageObj = {
        toName: toName || null,
        message: message
      };
      socket.send(JSON.stringify(messageObj));
      // 显示自己发送的消息
      const chat = document.getElementById('chat');
      const messageElement = document.createElement('div');
      messageElement.className = 'message sent';
      messageElement.innerHTML = `<strong>${username}:</strong> ${message}`;
      chat.appendChild(messageElement);
      chat.scrollTop = chat.scrollHeight;
      messageInput.value = '';
    }
  });
</script>
</body>
</html>
